
import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;


public class MainWindow extends javax.swing.JFrame implements Runnable, SpiderReport {

    protected Thread thread;
    protected Spider spider;
    protected URL base;
    protected int zlelinky = 0;
    protected int dobrelinky = 0;
    protected Collection stranky = new ArrayList();

    public MainWindow() {
        initComponents();
        setTitle("Spider");
    }

    @Override
    public void run() {
        try {
            jTextArea1.setText("");
            jTextArea2.setText("");
            jTextArea3.setText("");
            jTextArea4.setText("");
            String adress = jTextField1.getText();
            spider = new Spider(this);
            spider.clear();
            base = new URL(adress);
            spider.addURL(base);
            spider.begin();
            Runnable doLater = new Runnable() {

                @Override
                public void run() {
                    jButton1.setText("Štart");
                }
            };
            SwingUtilities.invokeLater(doLater);
            thread = null;

        } catch (MalformedURLException e) {
            thread = null;
            jButton1.setText("Štart");
            MainWindow.UpdateErrory err = new MainWindow.UpdateErrory();
            err.msg = "Bad address.";
            SwingUtilities.invokeLater(err);

        }
    }

    @Override
    public boolean spiderNasielURL(URL base, URL url) {
        MainWindow.UpdateStav cs = new MainWindow.UpdateStav();
        cs.msg = url.toString();
        SwingUtilities.invokeLater(cs);

        if (!checkLink(url)) {
            MainWindow.UpdateErrory err = new MainWindow.UpdateErrory();
            err.msg = url + "(na stránke " + base + ")\n";
            SwingUtilities.invokeLater(err);
            zlelinky++;
            return false;
        }

        dobrelinky++;
        if (!url.getHost().equalsIgnoreCase(base.getHost())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void spiderURLError(URL url) {
    }

    protected boolean checkLink(URL url) {
        try {
            URLConnection connection = url.openConnection();
            connection.connect();
            return true;
        } catch (IOException e) {
            MainWindow.UpdateErrory er = new MainWindow.UpdateErrory();
            er.msg = e.toString() + ":\n";
            SwingUtilities.invokeLater(er);
            return false;
        }
    }

    @Override
    public void spiderLog(String log) {
        MainWindow.UpdateLog em = new MainWindow.UpdateLog();
        em.msg = log;
        SwingUtilities.invokeLater(em);
    }

    @Override
    public void spiderNasielEMail(String email) {
        StringBuilder sb = new StringBuilder();
        email = email.substring(email.indexOf("mailto:")+7);
        if (email.indexOf("?") != -1) {
            sb.append(email.substring(0, email.indexOf("?")));
            sb.append("\n");
            email = email.substring(email.indexOf("?") + 1);
            while (email.indexOf("cc=") != -1) {

                if (email.indexOf("&") != -1) {
                    if (email.indexOf("cc=") < email.indexOf("&")) {
                        sb.append(email.substring(email.indexOf("cc=") + 3, email.indexOf("&")));
                        sb.append("\n");
                        email = email.substring(email.indexOf("&") + 1);
                    }
                } else if (email.indexOf("cc=") != -1) {
                    sb.append(email.substring(email.indexOf("cc=") + 3));
                    sb.append("\n");
                    email = email.substring(email.indexOf("cc=") + 3);
                }
            }
        } else {
            sb.append(email);
            sb.append("\n");
        }
        MainWindow.UpdateEMaily em = new MainWindow.UpdateEMaily();
        em.msg = sb.toString();
        SwingUtilities.invokeLater(em);
    }

    class UpdateLog implements Runnable {

        String msg;

        @Override
        public void run() {
            jTextArea3.append(msg);
            jTextArea3.append("\n");
            jTextArea3.setCaretPosition(jTextArea3.getDocument().getLength());
        }
    }

    class UpdateErrory implements Runnable {

        public String msg;

        @Override
        public void run() {
            jTextArea1.append(msg);
            jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
        }
    }

    class UpdateEMaily implements Runnable {

        public String msg;

        @Override
        public void run() {
            jTextArea2.append(msg);
            jTextArea2.setCaretPosition(jTextArea2.getDocument().getLength());
        }
    }

    class UpdateStav implements Runnable {

        public String msg;

        @Override
        public void run() {
            try {
                URL u = new URL(msg);
                if (!base.getHost().equals(u.getHost()) && !stranky.contains(u.getHost())) {
                    //ostatné stránky
                    stranky.add(u.getHost());
                    jTextArea4.append("http://" + u.getHost() + "\n");
                    jTextArea4.setCaretPosition(jTextArea4.getDocument().getLength());
                }
            } catch (MalformedURLException ex) {
            }
            jLabel2.setText("Aktuálne sa prehľadáva: " + msg);
            jLabel4.setText("Dobré linky: " + dobrelinky);
            jLabel5.setText("Slepé linky: " + zlelinky);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextArea4 = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Štart");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("URL:");

        jLabel2.setText("Aktuálne sa prehľadáva:");

        jLabel4.setText("Dobré linky: 0");

        jLabel5.setText("Slepé linky: 0");

        jScrollPane1.setAutoscrolls(true);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel3.setText("EMaily:");

        jScrollPane2.setAutoscrolls(true);

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jScrollPane2.setViewportView(jTextArea2);

        jScrollPane3.setAutoscrolls(true);

        jTextArea3.setColumns(20);
        jTextArea3.setRows(5);
        jScrollPane3.setViewportView(jTextArea3);

        jLabel6.setText("Výpis:");

        jTextArea4.setColumns(20);
        jTextArea4.setRows(5);
        jScrollPane4.setViewportView(jTextArea4);

        jLabel7.setText("Iné weby:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(122, 122, 122)
                                .addComponent(jLabel5))
                            .addComponent(jLabel3)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
                            .addComponent(jScrollPane1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE))
                    .addComponent(jScrollPane3)
                    .addComponent(jScrollPane4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (thread == null) {
            if (jTextField1.getText().isEmpty()) {
                return;
            }
            jButton1.setText("Koniec");
            thread = new Thread(this);
            thread.start();
            dobrelinky = 0;
            zlelinky = 0;
        } else {
            spider.cancel();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextArea jTextArea3;
    private javax.swing.JTextArea jTextArea4;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
